<template>
  <section class="decoration-edit">
    <section class="l">
      <ul @dragstart="dragStart" @dragend="dragEnd">
        <li
          v-for="(val, key, index) in typeList"
          :draggable="true"
          :data-type="key"
          :key="index + 1"
        >
          <!-- <span :class="val.icon"></span> -->
          <Icon :icon="val.icon" />
          <p>{{ val.name }}</p>
        </li>
      </ul>
    </section>
    <section class="c">
      <!-- header 不可拖拽 -->
      <!-- @click="selectType(0)" -->
      <div class="top-nav">
        <img src="../../../assets/images/topNavBlack.png" />
        <span class="tit">首页</span>
      </div>
      <div class="view-content" @drop="drog" @dragover="dragOver">
        <!-- :style="{ backgroundColor: info.backgroundColor }" -->
        <Draggable :list="view">
          <template #item="{ element, index }">
            <div class="item" @click="selectType(index)">
              <div class="wait" v-if="element.status && element.status == 2">{{
                element.type
              }}</div>
              <div v-else>
                <component
                  :is="typeList[element.type]['com']"
                  :data="element"
                  :className="className[element.tabType]"
                ></component>
              </div>
              <p @click="deleteItem($event, index)" class="el-icon-error">
                <Icon icon="simple-line-icons:close" />
              </p>
              <!-- <i @click="deleteItem($event, index)"  class="el-icon-error"></i> -->
            </div>
          </template>
        </Draggable>
      </div>
    </section>
    <section class="r">
      <EditForm :data="props" v-if="isRight"></EditForm>
    </section>

    <div class="submit-btn">
      <el-button @click="submit">提交页面</el-button>
    </div>
  </section>
</template>

<script lang="ts" setup>
  import { Icon } from '/@/components/Icon';
  import Draggable from 'vuedraggable';
  import EditForm from '/@/components/Edit/index.vue';
  import Product from '/@/components/View/Product.vue';
  import ProductSell from '/@/components/View/ProductSell.vue';
  // import Images from '/@/components/View/Images.vue';
  import HomeBanner from '/@/components/View/HomeBanner.vue';
  import HomeClassify from '/@/components/View/HomeClassify.vue';
  import TitleImages from '/@/components/View/TitleImages.vue';
  import { ElMessage } from 'element-plus';
  import { reactive, ref, computed, nextTick, watch } from 'vue';
  import { homeSave, homeForm } from '/@/api/shop/shop';
  import { useGlobSetting } from '/@/hooks/setting';

  const { ctxPath } = useGlobSetting();

  const props2 = defineProps({
    homeId: { type: String, default: '' },
    cversion: { type: String, default: '' },
  });
  watch(
    () => props2.homeId,
    () => {
      listData(props2.homeId);
    },
    {
      immediate: true,
    },
  );

  let typeList = reactive({
    homeBanner: {
      name: '首页轮播图',
      icon: 'simple-line-icons:picture',
      com: HomeBanner,
    },
    homeClassify: {
      name: '产品系列',
      icon: 'simple-line-icons:picture',
      com: HomeClassify,
    },
    titleImages: {
      name: '标题图片',
      icon: 'simple-line-icons:picture',
      com: TitleImages,
    },
    product: {
      name: '商品',
      icon: 'simple-line-icons:briefcase',
      com: Product,
    },
    productSell: {
      name: '促销',
      icon: 'simple-line-icons:briefcase',
      com: ProductSell,
    },

    footImages: {
      name: '底部图片',
      icon: 'simple-line-icons:picture',
      com: TitleImages,
    },

    // images: {
    //   name: '图片',
    //   icon: 'simple-line-icons:picture',
    //   com: Images,
    // },
  });

  let view: any = reactive([]);
  let title: any = ref('页面标题');
  let type: any = ref('');
  let areaType: any = ref('');
  let index: any = ref(null);
  let isPush = ref(false);
  let props: any = reactive({});
  let className: any = reactive({
    1: 'one',
    2: 'two',
    3: 'three',
  });
  let isRight: any = ref(false);
  let id: any = ref('');

  const info = computed(() => {
    // return view[0];
    return {
      type: 'info',
      title: '页面标题',
    };
  });
  async function listData(ids) {
    let res = await homeForm({ id: ids });
    if (view.length) {
      view.splice(0, view.length);
    }
    isRight.value = false;
    id.value = res.shopAppsetHome.id;
    console.log(res.shopAppsetHome.areaList);
    // isPush.value = true;
    if (!res.shopAppsetHome.isNewRecord) {
      res.shopAppsetHome.areaList.forEach((item) => {
        let type = '';
        if (item.areaType == '1') {
          type = 'homeBanner';
          let obj = {
            type,
            status: '',
            areaType: item.areaType,
            options: {},
            data: item.picList.map((item1) => {
              return {
                url: ctxPath + item1.picUrl,
                fileUpload: {
                  id: item1.fileId,
                  fileUrl: item1.picUrl,
                },
                remarks: item1.picRemarks,
                busKey: item1.busKey,
                busName: item1.busName,
                link: item1.jumpUrl,
                type: item1.busType,
              };
            }),
          };
          view.push(obj);
        }
        if (item.areaType == '2') {
          type = 'homeClassify';
          let obj = {
            type,
            status: '',
            areaType: item.areaType,
            options: {},
            data: item.proClsList.map((item1) => {
              return {
                picUrl: item1.proCls.picUrl,
                treeNames: item1.proCls?item1.proCls.name:'',
                parentCode: item1.proCls?item1.proCls.code:'',
                parentName: item1.proCls?item1.proCls.name:'',
                code: item1.proCls?item1.proCls.code:'',
                name: item1.proCls?item1.proCls.name:''
              };
            }),
          };
          view.push(obj);
        }
        if(item.areaType == '3'){
          type ='productSell'
          let obj = {
            type,
            status: '',
            areaType: item.areaType,
            options: {},
            data: item.sellList.map((item1) => {
              return {
                // picUrl: item1.proSell.picUrl? item1.proSell.picUrl :'https://img.quanminyanxuan.com/other/21188f7a1e9340759c113aa569f96699.jpg?x-oss-process=image/resize,h_600,m_lfit',
                ...item1.proSell,
                // abbName:item1.proSell.ctitle
              };
            }),
          };
          view.push(obj);
        }
        if (item.areaType == '4') {
          type = 'product';
          let obj = {
            type,
            status: '',
            areaType: item.areaType,
            options: {},
            data: item.invList.map((item1) => {
              return {
                // picUrl: item1.basInv.picUrl?ctxPath + item1.basInv.picUrl :'https://img.quanminyanxuan.com/other/21188f7a1e9340759c113aa569f96699.jpg?x-oss-process=image/resize,h_600,m_lfit',
                ...item1.basInv
              };
            }),
          };
          view.push(obj);
        }
        if (item.areaType == '5') {
          type = 'titleImages';
          let obj = {
            type,
            status: '',
            areaType: item.areaType,
            options: {},
            data: [
              {
                name: item.name,
                url: ctxPath + item.picUrl,
                form: '',
                fileUpload: {
                  fileName: item.name,
                  fileUrl: item.picUrl,
                  id: item.fileId,
                },
                busKey: item.busKey,
                busName: item.busName,
                link: item.jumpUrl,
                type: item.busType,
              },
            ],
          };
          view.push(obj);
        }
        if (item.areaType == '99') {
          type = 'footImages';
          let obj = {
            type,
            status: '',
            areaType: item.areaType,
            options: {},
            data: [
              {
                name: item.name,
                url: ctxPath + item.picUrl,
                form: '',
                fileUpload: {
                  fileName: item.name,
                  fileUrl: item.picUrl,
                  id: item.fileId,
                },
                busKey: item.busKey,
                busName: item.busName,
                link: item.jumpUrl,
                type: item.busType,
              },
            ],
          };
          view.push(obj);
        }
      });
    }
    index.value = view.length;
  }

  async function submit() {
    // JSON 转换会丢失 formData
    const form = JSON.parse(JSON.stringify(view));

    if (form.length == 0) {
      ElMessage.error('请添加模块！');
      return;
    }

    for (let i of form) {
      if (i.data && i.data.length == 0) {
        ElMessage.error('请填写完整信息！');
        return;
      }
      // if (i.type === 'product') {
      //   i.data = i.data.map((val) => val.productId).join(',');
      // }
    }

    // ElMessage.success('提交成功！');
    console.log(form); // 提交的数据，根据接口形式修改
    let areaList = form.map((item) => {
      let obj = {};

      if (item.areaType == '1') {
        obj = {
          areaType: item.areaType,
          picList: item.data.map((i) => {
            return {
              fileId: i.fileUpload.id,
              picUrl: i.fileUpload.fileUrl,
              picRemarks: i.remarks,
              jumpUrl: i.link,
              busType: i.type,
              busKey: i.busKey,
              busName: i.busName,
            };
          }),
        };
      }

      if (item.areaType == '2') {
        obj = {
          areaType: item.areaType,
          proClsList: item.data.map((i) => {
            return {
              clsCode: i.code,
              clsName: i.name,
            };
          }),
        };
      }

      if (item.areaType == '3') {
        obj = {
          areaType: item.areaType,
          sellList: item.data.map((i) => {
            return {
              sellId: i.id,
            };
          }),
        };
      }

      if (item.areaType == '4') {
        obj = {
          areaType: item.areaType,
          invList: item.data.map((i) => {
            return {
              invCode: i.cinvcode,
              invName: i.cinvname,
            };
          }),
        };
      }


      if (item.areaType == '5' || item.areaType == '99') {
        obj = {
          areaType: item.areaType,
          picUrl: item.data[0].fileUpload.fileUrl,
          fileId: item.data[0].fileUpload.id,
          jumpUrl: item.data[0].link,
          busType: item.data[0].type,
          busKey: item.data[0].busKey,
          busName: item.data[0].busName,
        };
      }

      return obj;
    });

    let data = {
      id: props2.homeId,
      cversion: props2.cversion,
      areaList,
    };
    console.log(data, 'data更改后数据-==========');

    try {
      const res = await homeSave(data);
      console.log(res);
      ElMessage.success(res.message);
    } catch (error: any) {
      if (error || error.errorFields) {
        ElMessage.error('保存失败！');
      }
      console.log('error', error);
    } finally {
    }
  }

  function selectType(index) {
    console.log(index, 'selectType==');
    console.log(view, 'view=====');

    isRight.value = false;
    props = view[index];
    nextTick(() => (isRight.value = true));
  }
  function deleteItem(e, index) {
    console.log(index, e, '删除======');

    e.preventDefault();
    e.stopPropagation();
    view.splice(index, 1);
    isRight.value = false;
    props = {};
  }
  function dragStart(e) {
    type.value = e.target.dataset.type;
    if (type.value == 'homeBanner') {
      areaType.value = '1';
    }
    if (type.value == 'homeClassify') {
      areaType.value = '2';
    }
    if(type.value == 'productSell'){
      areaType.value = '3'
    }
    if (type.value == 'product') {
      areaType.value = '4';
    }
    if (type.value == 'titleImages') {
      areaType.value = '5';
    }
    if (type.value == 'footImages') {
      areaType.value = '99';
    }
  }
  function dragEnd() {
    view.forEach((item) => {
      if (item && item.status) {
        item['status'] = '';
      }
    });
    isPush.value = false;
    type.value = null;
  }
  function drog(e) {
    if (!type.value) {
      // 内容拖拽
      return;
    }
    e.preventDefault();
    e.stopPropagation();
    dragEnd();
  }
  function dragOver(e) {
    // console.log(e.target.__draggable_context,'1111111111111dragOver');

    if (!type.value) {
      // 内容拖拽
      return;
    }
    e.preventDefault();
    e.stopPropagation();

    let className = e.target.className;
    let name = className !== 'view-content' ? 'item' : 'view-content';

    let defaultData = {
      type: type.value, // 组件类型
      status: 2, // 默认状态
      data: [], // 数据
      areaType: areaType.value, //区域类型
      options: {}, // 选项操作
    };
    if (name == 'view-content') {
      if (!isPush.value) {
        index.value = view.length;
        isPush.value = true;
        view.push(defaultData);
      }
    } else if (name == 'item') {
      let target = e.target;
      // if(!target.__draggable_context){
      //   console.log(target);
      //   console.log(target.__draggable_context);
      //   console.log(333333333333);
      //   return
      // }
      // console.log(444444444444);
      let [y, h, curIndex] = [e.offsetY, target.offsetHeight, target.__draggable_context.index];
      let direction = y < h / 2;

      if (!isPush.value) {
        // Push to Top or Bottom
        if (direction) {
          if (curIndex == 0) {
            view.unshift(defaultData);
          } else {
            view.splice(curIndex, 0, defaultData);
          }
        } else {
          curIndex = +curIndex + 1;
          view.splice(curIndex, 0, defaultData);
        }
      } else {
        // Moving
        if (direction) {
          var i = curIndex == 0 ? 0 : curIndex - 1;
          var result = view[i]['status'] == 2;
        } else {
          var i = +curIndex + 1;
          var result = view.length > i && view[i]['status'] == 2;
        }

        if (result) return;

        const temp = view.splice(index.value, 1);
        view.splice(curIndex, 0, temp[0]);
      }
      index.value = curIndex;
      isPush.value = true;
    }
  }
</script>
<style lang="less">
  .decoration-edit {
    display: flex;
    align-items: center;
    justify-content: space-between;
    // padding: 10px 0;
    background: #f7f8f9;
    height: calc(100vh - 120px);
    position: relative;
    .l,
    .r {
      width: 340px;
      height: 100%;
      padding: 15px 0;
      background: #fff;
    }
    .l {
      ul {
        margin: 0;
        padding: 0;
        li {
          width: 80px;
          height: 80px;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          cursor: default;
          list-style: none;
          font-size: 14px;
          color: #666;
          float: left;
          margin: 0 10px;
          border-radius: 6px;
          transition: all 0.3s;
          cursor: pointer;
          &:hover {
            background: #efefef;
          }
          span {
            display: block;
            font-size: 40px;
            margin-bottom: 8px;
            color: #999;
          }
          p {
            display: block;
            margin: 0;
            font-size: 12px;
          }
        }
      }
    }
    .c {
      width: auto;
      max-width: 400px;
      position: relative;
      .top-nav {
        position: absolute;
        top: 0;
        background: #fff;
        z-index: 999;
        transition: all 0.3s;
        & * {
          pointer-events: none;
        }
        &:hover {
          transform: scale(0.95);
          border-radius: 10px;
          overflow: hidden;
          box-shadow: 0 0 10px #afafaf;
        }
        .tit {
          position: absolute;
          left: 50%;
          bottom: 10px;
          transform: translateX(-50%);
        }
        img {
          max-width: 100%;
          image-rendering: -moz-crisp-edges;
          image-rendering: -o-crisp-edges;
          image-rendering: -webkit-optimize-contrast;
          image-rendering: crisp-edges;
          -ms-interpolation-mode: nearest-neighbor;
        }
      }
      .view-content {
        width: 400px;
        height: 700px;
        background: #f5f5f5;
        overflow-y: auto;
        overflow-x: hidden;
        padding-top: 72px;
        box-shadow: 0 2px 6px #ccc;
        &::-webkit-scrollbar {
          width: 6px;
        }
        &::-webkit-scrollbar-thumb {
          background: #dbdbdb;
        }
        &::-webkit-scrollbar-track {
          background: #f6f6f6;
        }

        .item {
          transition: all 0.3s;
          background: #fff;
          &:hover {
            transform: scale(0.95);
            border-radius: 10px;
            box-shadow: 0 0 10px #afafaf;
            .el-icon-error {
              display: block;
            }
          }
          div {
            pointer-events: none;
          }
          .wait {
            background: #deedff;
            height: 35px;
            text-align: center;
            line-height: 35px;
            font-size: 12px;
            color: #666;
          }
          .el-icon-error {
            position: absolute;
            right: 0px;
            top: -6px;
            color: red;
            // background: red;
            font-size: 25px;
            cursor: pointer;
            display: none;
            z-index: 9999;
          }
        }
      }
    }
    .submit-btn {
      position: absolute;
      bottom: 30px;
      left: 50%;
      transform: translateX(-50%);
    }
  }
</style>
